﻿using MediatR;
using Sgr.Caching.Services;
using Sgr.Domain.Uow;
using Sgr.UPMS.Application.Services;
using Sgr.UPMS.Domain.Users;
using Sgr.UPMS.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Sgr.UPMS.Application.DomainEventHandlers
{
    public class OrganizationCancellationDomainEventHandle : INotificationHandler<OrganizationCancellationDomainEvent>
    {
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        private readonly IOrgBasicDataCacheService _orgBasicDataCacheService;

        public OrganizationCancellationDomainEventHandle(
             IUnitOfWorkManager unitOfWorkManager,
             IOrgBasicDataCacheService orgBasicDataCacheService)
        {
            _orgBasicDataCacheService = orgBasicDataCacheService;
            _unitOfWorkManager = unitOfWorkManager;
        }

        public async Task Handle(OrganizationCancellationDomainEvent notification, CancellationToken cancellationToken)
        {
            Task clearCacheAsync()
            {
                return _orgBasicDataCacheService.RemoveOrgAllCacheAsync(notification.OrgId);
            }

            if (_unitOfWorkManager.Current != null && !_unitOfWorkManager.Current.IsCompleted)
                _unitOfWorkManager.Current.AddCompletedHandler(clearCacheAsync);
            else
                await clearCacheAsync();
        }
    }
}